﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_StationBusiness : BaseBusiness<PB_Station>, IPB_StationBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_StationBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_StationDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
          
            var search = input.Search;
            Expression<Func<PB_Station, Base_Department, PB_Workshop, PB_StationDTO>> select = (a, b, c) => new PB_StationDTO
            {
                DepartmentName = b.Name,
                WorkshopName = c.Name,
            
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Workshop>() on a.WorkshopId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                  
                    select @select.Invoke(a, b, c);

            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Name, keyword)
                      || EF.Functions.Like(x.Code, keyword));
            }
            q = q.Where(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.GetPageResultAsync(input);
        }

        /// <summary>
        /// 根据车间ID查询工位信息
        /// </summary>
        /// <param name="workshopId">车间编码</param>
        /// <returns></returns>
        public async Task<PageResult<PB_Station>> GetDataListByWorkshopAsync(string workshopId)
        {
            var q = GetIQueryable();

            var where = LinqHelper.True<PB_Station>();

            if (!workshopId.IsNullOrEmpty())
            {
                where = where.And(w => w.WorkshopId==workshopId);
            }

            return await q.Where(where).GetPageResultAsync(new PageInput());
        }

        public async Task<PB_Station> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataRepeatValidate(new string[] { "Code" }, new string[] { "编号" })]
        public async Task AddDataAsync(PB_Station data)
        {
            data.QrCode = h_Station + "," + data.Id + "," + data.DeptId + "," + data.WorkshopId;
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_Station data)
        {
            data.QrCode = h_Station + "," + data.Id + "," + data.DeptId + "," + data.WorkshopId;
            await UpdateAsync(data);
        }
        [DataDeleteLog(UserLogType.工位管理, "Name", "工位管理")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<PageResult<PB_Station>> GetDataListByDepartmentAsync(string DeptId)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_Station>();

            //筛选
            if (!DeptId.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Station, bool>(
                    ParsingConfig.Default, false, $@"DeptId.Equals(@0)", DeptId);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(new PageInput());
        }

        public async Task<AjaxResult> SelectStationID(string ID, MongoDBOptions _mongodbOptions)
        {
            try
            {
                string[] arr = ID.Split(',');
                List<string> List = new List<string>();
                foreach (var item in arr)
                {
                    List.Add(item);
                }
                var q = GetIQueryable();
                List<PrintQueue> printqueue = new List<PrintQueue>();
                var res = q = q.Where(m => List.Contains(m.Id));
                var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
                foreach (var item in res)
                {
                    PB_Station station = new PB_Station();
                    PrintQueue printdata = new PrintQueue();
                    printdata.Id = IdHelper.GetId();
                    printdata.No = item.Code;//编号
                    printdata.Name = item.Name;
                    printdata.TypeName = "";
                    printdata.Dept = k.Name;//当前登录人所在组织
                    printdata.QrCode = item.QrCode;//工位
                    printdata.Type = Skill_Type.Station.ToString();//工位
                    printdata.Status = "0";
                    printdata.Printer = _operator?.Property.Printer;
                    printqueue.Add(printdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, printqueue);
                AjaxResult resIn = new AjaxResult
                {
                    Success = true,
                    Msg = "打印成功"
                };
                return resIn;
            }
            catch (Exception)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "打印失败！数据错误请检查数据"
                };
                return res;
            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}